<?php

declare(strict_types=1);

namespace app\admin\middleware;

class CheckParams
{
    public function handle($request, \Closure $next)
    {
        switch (strtoupper($request->method())) {
            case 'GET':
                $request->params = $request->param() ? $this->cleanParams($request->param()) : $this->cleanParams($request->post());
                break;
            case 'POST':
                $request->params = $this->cleanParams($request->post());
                break;
            case 'PUT':
                $request->params = $this->cleanParams($request->param());
                break;
            case 'DELETE':
                $request->params = $this->cleanParams($request->post());
                break;

            default:
                # code...
                break;
        }

        return $next($request);
    }

    /**
     * 清理参数数组
     *
     * @param array $params
     * @return array
     */
    protected function cleanParams($params)
    {
        foreach ($params as $key => &$value) {

            switch (strtoupper(gettype($value))) {
                case 'ARRAY':
                    $value = $this->cleanParams($value);
                    break;
                case 'STRING':
                    if (!is_null($value)) {
                        $value = trim(htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8'));
                    }
                    break;
                default:
                    # code...
                    break;
            }

            // 这里可以根据需要添加更多的过滤条件

        }
        return $params;
    }
}
